import type { ProColumns } from '@/components/Pro/';
import { ProTable } from '@/components/Pro/';
import { currentControllerGetClusterCurrentData } from '@/services/ess/healthCurrent';
import { useIntl } from '@umijs/max';
import ReactEcharts from 'echarts-for-react';
import React, { useEffect, useRef, useState } from 'react';
import Styles from '../index.less';

interface DataItem {
  clusterName: string;
  max: number;
  time: string;
}

interface addProps {
  activeKey?: string;
  date?: string;
  yuValue?: string;
  activeName?: string;
}

const Index: React.FC<addProps> = ({ activeKey, date, yuValue, activeName }) => {
  const intl = useIntl();
  const [pageData, setPageData] = useState<{
    seriesData: any[];
    arrXtest: string[];
    dataAverage: number[];
    maxCirculationCurrent: string;
    maxCirculationCurrentTime: string;
    maxItem?: number;
    minItem?: number;
  }>({
    seriesData: [],
    arrXtest: [],
    dataAverage: [],
    maxCirculationCurrent: '',
    maxCirculationCurrentTime: '',
  });
  const [isEmpty, setEmpty] = useState(true);
  const [ProTableData, setProTableData] = useState<
    {
      clusterName?: string;
      max?: number;
      time?: string;
    }[]
  >([]);
  const chartRef = useRef();
  let dataAverage: number[] = [];
  let maxCirculationCurrent: number | string = pageData?.maxCirculationCurrent || '';
  let maxCirculationCurrentTime: string = pageData?.maxCirculationCurrentTime || '';
  let maxItem: number = 0;
  let minItem: number = 0;

  const initEmpty = () => {
    setEmpty(true);
    setPageData({
      seriesData: [],
      arrXtest: [],
      dataAverage: [],
      maxCirculationCurrent: '',
      maxCirculationCurrentTime: '',
    });
  };

  const tableColumns: ProColumns<DataItem>[] = [
    {
      dataIndex: 'clusterName',
      key: 'clusterName',
      hideInSearch: true,
      title: intl.formatMessage({ id: 'data.batteryStackName' }),
    },
    {
      title: intl.formatMessage({ id: 'batteryVoltage.tips.cluFourth' }),
      dataIndex: 'max',
      key: 'max',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'batteryVoltage.tips.cluFifth' }),
      dataIndex: 'time',
      key: 'time',
      hideInSearch: true,
    },
  ];
  useEffect(() => {
    if (activeKey !== '') {
      currentControllerGetClusterCurrentData({
        date: date,
        bmsCode: activeKey,
      }).then((reslut) => {
        if (reslut.data?.circulationInfo !== null && reslut.data?.circulationInfo.length) {
          chartRef?.current?.getEchartsInstance()?.clear();
          const EchartObj = {
            //存储echarts相应对象
            xData: [],
            seriers: [],
          };
          let nothasNullData = [];
          let arrMax: number[] = []; //存储最大环流差
          let allData: number[] = [];

          for (let item of Object.values(reslut.data.circulationInfo)) {
            if (nothasNullData.length === 0) {
              if (!item.currentData.some((res) => res === null)) {
                nothasNullData = item.currentData;
              }
            }
          }

          for (let i = 0; i < nothasNullData.length; i++) {
            let item = nothasNullData[i];
            EchartObj.seriers.push({
              name: item.clusterName,
              data: [],
              type: 'line',
              symbolSize: 0,
            });
          }

          for (let [key, item] of Object.entries(reslut.data.circulationInfo)) {
            reslut.data.circulationInfo[key]['currentData'] = item.currentData.map((res, index) => {
              if (res === null) {
                return {
                  clusterName: nothasNullData[index]['clusterName'],
                  current: null,
                };
              } else {
                return res;
              }
            });
            EchartObj.xData.push(item.dateTime);
          }

          for (let item of Object.values(reslut.data.circulationInfo)) {
            arrMax = arrMax.concat(item.currentData);
            allData = allData.concat(item.currentData);
          }

          for (let i = 0; i < EchartObj.seriers.length; i++) {
            EchartObj.seriers[i]['data'] = allData
              .map((res) => {
                if (EchartObj.seriers[i]['name'] === res.clusterName) {
                  return res.current;
                } else {
                  return 'NOdata';
                }
              })
              .filter((res) => res !== 'NOdata');
          }
          maxItem = Math.max(...arrMax.map((res) => (res.current !== null ? res.current : 0)));
          minItem = Math.min(...arrMax.map((res) => (res.current !== null ? res.current : 0)));
          dataAverage = (reslut.data.circulationInfo || []).map((res) => res.average);

          EchartObj.seriers.unshift({
            name: '平均值',
            type: 'line',
            data: dataAverage,
            label: {
              show: false,
              formatter: '平均值',
            },
            itemStyle: {
              color: '#c7d0e0',
            },
            lineStyle: {
              width: 1,
            },
            symbolSize: 0,
          });
          let seriesData = EchartObj.seriers.map((res) => {
            res.markLine = {
              silent: true,
              lineStyle: {
                normal: {
                  type: 'dashed',
                  color: 'gray',
                  width: 2, // 设置线的宽度
                },
              },
              data: [
                [
                  {
                    coord: [reslut.data?.startTime, minItem],
                    symbol: 'none',
                    name: intl.formatMessage({ id: 'batteryVoltage.tips.cluSixth' }),
                    label: {
                      offset: [0, -5],
                      color: 'orange',
                      borderWidth: 4,
                    },
                  },
                  {
                    coord: [reslut.data?.startTime, maxItem],
                    symbol: 'arrow',
                  },
                ],
              ],
            };

            return res;
          });

          let arrXtest = EchartObj.xData;

          setEmpty(false);

          setPageData({
            arrXtest: arrXtest,
            dataAverage: dataAverage,
            seriesData: seriesData,
            maxCirculationCurrent: reslut.data.maxCurrentDiff || '',
            maxCirculationCurrentTime: reslut.data.startTime || '',
            minItem: minItem,
            maxItem: maxItem,
          });
          setProTableData([
            {
              clusterName: activeName,
              max: reslut?.data?.maxCurrentDiff,
              time: `${reslut.data.startTime} ${intl.formatMessage({
                id: 'batteryVoltage.vol.to',
              })} ${reslut.data.endTime}`,
            },
          ]);
        } else {
          chartRef?.current?.getEchartsInstance()?.clear();
          initEmpty();
          setProTableData([{ clusterName: activeName, max: '', time: '' }]);
        }
      });
    } else {
      chartRef?.current?.getEchartsInstance()?.clear();
      setProTableData([]);
      initEmpty();
    }
  }, [activeKey, date]);

  return (
    <>
      <ReactEcharts
        style={{ height: 450 }}
        ref={chartRef}
        option={{
          tooltip: {
            trigger: 'axis',
            formatter: function (params) {
              if (!isEmpty) {
                let li = '';
                let maxCirculationCurrentFormat =
                  maxCirculationCurrent !== '' &&
                  maxCirculationCurrent !== null &&
                  !isNaN(maxCirculationCurrent)
                    ? maxCirculationCurrent.toFixed(2)
                    : '';

                let ParamsAverage = params.filter((res) => res.seriesName === '平均值')[0]?.[
                  'data'
                ];
                for (let i = 0; i < params.length; i++) {
                  let value = params[i]['data'];
                  let valueFormat =
                    value !== '' && value !== null && !isNaN(value) ? value.toFixed(2) : '--';

                  if (value !== null) {
                    if (value >= ParamsAverage) {
                      if (params[i]['seriesName'] === '平均值') {
                        continue;
                      } else {
                        li += `<li>${params[i]['marker']}<span>${
                          params[i]['seriesName']
                        }</span><sapn>${intl.formatMessage({
                          id: 'batteryVoltage.tips.cluEigth',
                        })} ${valueFormat}</span>A<span style='color:red'>>=${intl.formatMessage({
                          id: 'batteryVoltage.tips.cluSevth',
                        })}</span></li>`;
                      }
                    } else {
                      li += `<li>${params[i]['marker']}<span>${
                        params[i]['seriesName']
                      }</span><sapn>${intl.formatMessage({
                        id: 'batteryVoltage.tips.cluEigth',
                      })} ${valueFormat}
                      </span>A<span style='color:#67C23A'><=${intl.formatMessage({
                        id: 'batteryVoltage.tips.cluSevth',
                      })}</span></li>`;
                    }
                  } else {
                    li += `<li>${params[i]['marker']}<span>${
                      params[i]['seriesName']
                    }</span><sapn>${intl.formatMessage({
                      id: 'batteryVoltage.tips.cluSevth',
                    })} ${valueFormat}</span></li>`;
                  }
                }
                return `<div style="background-color: #fff; padding: 10px;">${
                  params[0]['axisValue']
                } &nbsp;&nbsp;${intl.formatMessage({
                  id: 'batteryVoltage.tips.cluFourth',
                })}${maxCirculationCurrentFormat}A&nbsp;&nbsp;${maxCirculationCurrentTime}</div><ul>${li}</ul>`;
              }
            },
          },
          legend: {
            show: pageData?.seriesData?.length ? true : false,
            right: '0',
          },
          color: [
            '#6e59f3',
            '#1a55fe',
            '#1a6cfe',
            '#508fff',
            '#50ccff',
            '#3ac297',
            '#67c23a',
            '#ffd50c',
            '#ffa10c',
            '#ff7a0c',
            '#f5353',
            '#f5222d',
          ],
          grid: {
            left: '50px',
            right: '3%',
            bottom: '3%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            name: '',
            nameTextStyle: {
              //x轴单位颜色
              color: '#222',
            },
            boundaryGap: false,
            data: pageData?.arrXtest || [],
            axisLine: {
              lineStyle: {
                color: '#e0e0e0',
              },
            },
            lineStyle: {
              opacity: isEmpty ? 0 : 1,
            },
            axisLabel: {
              color: '#222222',
              formatter: function (value) {
                return value.substring(11, 16);
              },
              interval: 119,
            },
            axisTick: {
              show: true,
              inside: true,
              lineStyle: {
                color: '#e0e0e0',
              },
            },
          },
          yAxis: {
            type: 'value',
            name: 'A',
            min: pageData?.minItem,
            max: pageData?.maxItem,
            nameTextStyle: {
              //x轴单位颜色
              color: '#222',
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#e0e0e0',
              },
            },
            axisLabel: {
              color: '#222222',
            },
            axisTick: {
              show: true,
              inside: true,
              lineStyle: {
                color: '#e0e0e0',
              },
            },
          },
          dataZoom: [
            {
              type: 'inside',
            },
          ],
          series: pageData?.seriesData || [],
          graphic: [
            {
              type: 'image',
              silent: true,
              style: {
                image: require('@/assets/img/empty.png'),
                width: 180,
                height: 120,
              },
              bounding: 'raw',
              top: 'center',
              left: 'center',
              invisible: !isEmpty,
            },
            {
              type: 'text', // 类型：文本
              left: 'center',
              top: '65%',
              silent: true, // 不响应事件
              invisible: !isEmpty, // 有数据就隐藏
              style: {
                fill: '#222',
                text: intl.formatMessage({ id: 'global.noDataYet' }),
                fontFamily: 'Microsoft YaHei',
                fontSize: '14px',
              },
            },
          ],
        }}
      ></ReactEcharts>

      <ul className={Styles.descList_item3}>
        <li key="1">
          <span>{intl.formatMessage({ id: 'batteryVoltage.tips.socFor' })}：</span>
          1.{intl.formatMessage({ id: 'batteryVoltage.tips.cluThr' })}
          {yuValue}
          {intl.formatMessage({ id: 'batteryVoltage.tips.cluThrAfter' })}
        </li>
        <li style={{ marginLeft: 41 }} key="2">
          2.{intl.formatMessage({ id: 'batteryVoltage.tips.socSixteen' })}
        </li>
      </ul>
      <div className={Styles.tableWrap}>
        <ProTable
          columns={tableColumns}
          dataSource={ProTableData}
          search={false}
          rowKey={'pageIndex'}
          pagination={false}
        ></ProTable>
      </div>
    </>
  );
};

export default Index;
